﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using JN.Utility;
using DevExpress.XtraTreeList.Nodes;
using Power.BLL;
using Power.Common.DEncrypt;

namespace Power.UserInfo
{
    public partial class UserInfo : DevExpress.XtraEditors.XtraForm
    {
        #region property
        private Sys_userBLL userBLL = new Sys_userBLL();
        private bool isAdd;
        private string station_Id;
        #endregion
        public UserInfo()
        {
            InitializeComponent();
        }

        private void UserInfo_Load(object sender, EventArgs e)
        {
            using (new DevExpress.Utils.WaitDialogForm("正在加载数据...", "Please Wait..."))
            {
                station_Id = Manager.SystemStatus.Instance.Station_id;
                InitalizeUI();
                DisplayButton(false);
                EnanbleAllTextInput(false);
                LoadStationInfo();
                LoadRole();
            } 
        }
        /// <summary>
        /// 初始化界面，加载treelist
        /// </summary>
        private void InitalizeUI()
        {
            try
            {
                TreeListNode node;
                treeList1.Nodes.Clear();
                node = treeList1.AppendNode(new object[] { "人员信息", "人员信息", null, null }, null);
                node.StateImageIndex = 1;
                //node2 = tlstHead.AppendNode(new object[] { "Step Name", "Step Name", null, null }, null);

                //get data from table
                DataTable dtData;
                if (!string.IsNullOrEmpty(station_Id))
                {
                    //have zhan dian
                    dtData = userBLL.GetList(" station_id ='"+ station_Id +"' ").Tables[0];
                }
                else
                {
                    dtData = userBLL.GetAllList().Tables[0];
                }
                
                for (int i = 0; i < dtData.Rows.Count; i++)
                {
                    node = treeList1.AppendNode(new object[] { dtData.Rows[i]["user_id"] + "_" + dtData.Rows[i]["user_name"], dtData.Rows[i]["user_id"], null, null }, 0);
                    node.StateImageIndex = 0;

                    //node2 = tlstHead.AppendNode(new object[] { dtStep.Tables[0].Rows[i]["step_name"], i, null, null }, 1);
                }
                //node.ExpandAll();
                treeList1.ExpandAll();
                this.treeList1.EndUnboundLoad();

                DisplayForm("");    //initalize list 

            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        /// <summary>
        /// 按键显示
        /// </summary>
        /// <param name="isAdd"></param>
        private void DisplayButton(bool isAdd)
        {
            try
            {
                if (isAdd)
                {
                    btnAdd.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    btnQuery.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    btnDelete.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    btnEdit.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

                    btnSave.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                    btnCancel.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;

                }
                else
                {
                    btnAdd.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                    btnQuery.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                    btnDelete.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                    btnEdit.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;

                    btnSave.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    btnCancel.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

                    txtId.Enabled = true;
                    txtStation.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        /// <summary>
        /// 输入状态
        /// </summary>
        /// <param name="isCanInput"></param>
        private void EnanbleAllTextInput(bool isCanInput)
        {
            try
            {
                txtId.Properties.ReadOnly = !isCanInput;
                txtStation.Properties.ReadOnly = !isCanInput;
                txtName.Properties.ReadOnly = !isCanInput;
                txtEmail.Properties.ReadOnly = !isCanInput;
                txtPwd.Properties.ReadOnly = !isCanInput;
                txtPwd2.Properties.ReadOnly = !isCanInput;
                txtRemark.Properties.ReadOnly = !isCanInput;
                txtRole.Properties.ReadOnly = !isCanInput;
                txtTel.Properties.ReadOnly = !isCanInput;

            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        /// <summary>
        /// 显示界面信息
        /// </summary>
        /// <param name="eqGrpID"></param>
        private void DisplayForm(string userId)
        {
            try
            {
                if (userId != "")
                {
                    //get eq info     
                    Model.Sys_user mUser = userBLL.GetModel(userId);
                    if (mUser == null) return;

                    txtEmail.Text = mUser.email;
                    txtId.Text = mUser.user_id;
                    txtName.Text = mUser.user_name;
                    string pwd = DEncrypt.Decrypt(mUser.user_password);
                    txtPwd.Text = pwd;
                    txtPwd2.Text = pwd;
                    txtRemark.Text = mUser.remark;
                    txtRole.EditValue = mUser.user_role;
                    txtStation.EditValue = mUser.station_id;
                    txtTel.Text = mUser.telphone;
                }
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        /// <summary>
        /// 加载站点
        /// </summary>
        private void LoadStationInfo()
        {
            try
            {
                Station_infoBLL stationBLL = new Station_infoBLL();
                DataTable dtData = stationBLL.GetAllList().Tables[0];
                txtStation.Properties.ValueMember = "station_id";
                txtStation.Properties.DisplayMember = "station_name";
                txtStation.Properties.DataSource = dtData;
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        /// <summary>
        /// 加载角色
        /// </summary>
        private void LoadRole()
        {
            try
            {
                Sys_roleBLL roleBLL = new Sys_roleBLL();
                DataTable dtData = roleBLL.GetAllList().Tables[0];

                txtRole.Properties.ValueMember = "role_id";
                txtRole.Properties.DisplayMember = "role_desc";
                txtRole.Properties.DataSource = dtData;
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        private bool IsValid()
        {
            bool ret = false;
            try
            {
                if (string.IsNullOrEmpty(txtId.Text))
                {
                    XtraMessageBox.Show("请输入登录名");
                    return ret;
                }
                if (string.IsNullOrEmpty(txtName.Text))
                {
                    XtraMessageBox.Show("请输入姓名!");
                    return ret;
                }
                if (string.IsNullOrEmpty(txtPwd.Text))
                {
                    XtraMessageBox.Show("请输入密码!");
                    return ret;
                }
                if (string.IsNullOrEmpty(txtPwd2.Text))
                {
                    XtraMessageBox.Show("请输入确认密码!");
                    return ret;
                }
                if (txtPwd2.Text != txtPwd.Text)
                {
                    XtraMessageBox.Show("二次输入的密码不相同!");
                    return ret;
                }
                if (string.IsNullOrEmpty(txtRole.Text))
                {
                    XtraMessageBox.Show("请选择角色!");
                    return ret;
                }
                if (string.IsNullOrEmpty(txtStation.Text))
                {
                    XtraMessageBox.Show("请选择站点!");
                    return ret;
                }
                ret = true;
                return ret;
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
                return false;
            }
        }

        private void btnAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                isAdd = true;
                txtId.Text = "";
                txtStation.Text = "";
                txtEmail.Text = "";
                txtPwd.Text = "";
                txtPwd2.Text = "";
                txtRemark.Text = "";
                txtRole.Text = "";
                txtStation.Text = "";
                txtTel.Text = "";
                //init param
                LoadStationInfo();
                DisplayButton(true);
                EnanbleAllTextInput(true);
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }

        private void btnEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (txtId.Text.Trim() == "")
                {
                    XtraMessageBox.Show("请选择修改人员!!");
                    return;
                }
                isAdd = false;
                EnanbleAllTextInput(true);
                txtId.Enabled = false;
                txtStation.Enabled = false;
                DisplayButton(true);
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }

        private void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (txtId.Text == "")
            {
                XtraMessageBox.Show("请选择需要删除的人员");
                return;
            }
            DialogResult result = XtraMessageBox.Show("确认删除此人员信息??", "警告", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                if (userBLL.Delete(txtId.Text.Trim()))
                {
                    XtraMessageBox.Show("删除成功!!");
                }
                else
                {
                    XtraMessageBox.Show("删除失败!!");
                }
            }
            InitalizeUI();
        }

        private void btnQuery_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            using (new DevExpress.Utils.WaitDialogForm("正在加载数据...", "Please Wait..."))
            {
                InitalizeUI();
            } 
        }

        private void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (!IsValid())
            {
                return;
            }
            if (SaveData())
            {
                //refresh data
                XtraMessageBox.Show("保存成功!!");
                InitalizeUI();
                EnanbleAllTextInput(false);
                DisplayButton(false);
            }
            else
            {
                XtraMessageBox.Show("保存失败!!");
            }  
        }

        private void btnCancel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DisplayButton(false);
            EnanbleAllTextInput(false);
        }

        private bool SaveData()
        {
            bool ret = false;
            try
            {
                if (txtId.Text == "")
                {
                    XtraMessageBox.Show("请输入登录名!!");
                    return ret;
                }
                if (txtStation.EditValue.ToString() == "")
                {
                    XtraMessageBox.Show("请选站点!!");
                    return ret;
                }
                if (isAdd)
                {
                    if (userBLL.Exists(txtId.Text))
                    {
                        XtraMessageBox.Show("人员已经存在，请重新输入!!");
                        txtId.Focus();
                        return ret;
                    }

                    //save param                    
                    Model.Sys_user mUser = new Model.Sys_user();

                    mUser.email = txtEmail.Text;
                    mUser.remark = txtRemark.Text;
                    mUser.station_id = txtStation.EditValue.ToString();
                    mUser.telphone = txtTel.Text;
                    mUser.user_id = txtId.Text;
                    mUser.user_name = txtName.Text;
                    string pwd = DEncrypt.Encrypt(txtPwd.Text);
                    mUser.user_password = pwd;
                    mUser.user_role = txtRole.EditValue.ToString();                    

                    //add new step
                    ret = userBLL.Add(mUser);
                    return ret;
                }
                else
                {

                    //save param                    
                    Model.Sys_user mUser = userBLL.GetModel(txtId.Text);

                    mUser.email = txtEmail.Text;
                    mUser.remark = txtRemark.Text;
                    mUser.station_id = txtStation.EditValue.ToString();
                    mUser.telphone = txtTel.Text;
                    mUser.user_id = txtId.Text;
                    mUser.user_name = txtName.Text;
                    string pwd = DEncrypt.Encrypt(txtPwd.Text);
                    mUser.user_password = pwd;
                    mUser.user_role = txtRole.EditValue.ToString();

                    //add new step
                    ret = userBLL.Update(mUser);
                    return ret;
                }
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
                return false;
            }
        }

        private void treeList1_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnSave.Visibility == DevExpress.XtraBars.BarItemVisibility.Always)
                {
                    XtraMessageBox.Show("正在修改模式，不能切换!");
                    return;
                }
                TreeListNode clickedNode = this.treeList1.FocusedNode;
                string disPlayText = clickedNode.GetDisplayText(0);
                if (disPlayText.ToUpper() != "人员信息s")
                {
                    DisplayForm(disPlayText.Substring(0, clickedNode.GetDisplayText(0).IndexOf("_")));
                }
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }

        private void txtRole_Click(object sender, EventArgs e)
        {
            LoadRole();
            txtRole.ShowPopup();
        }

        private void txtStation_Click(object sender, EventArgs e)
        {
            LoadStationInfo();
            txtStation.ShowPopup();
        }
    }
}